//
//  GKLocationManager.m
//  ZeroDistance
//
//  Created by Jeffrey on 15/7/11.
//  Copyright (c) 2015年 woodare. All rights reserved.
//

#import "GKLocationManager.h"

@interface GKLocationManager()<CLLocationManagerDelegate>
{
    CLLocationManager *_cllocationManager;
    
}
@property (nonatomic, copy) GKFetchLocationCompledBlock locationCompled;

@end

@implementation GKLocationManager

+ (instancetype)manager {
    static GKLocationManager *_locationManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _locationManager = [[GKLocationManager alloc] init];
    });
    
    return _locationManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _cllocationManager = [[CLLocationManager alloc] init];
        _cllocationManager.delegate = self;
        CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
        if(status == kCLAuthorizationStatusNotDetermined || status == kCLAuthorizationStatusAuthorized){
            if(kCurrentSystemVersion>=8.0)
            {
                if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){
                    [_cllocationManager requestAlwaysAuthorization];
                } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
                    [_cllocationManager  requestWhenInUseAuthorization];
                } else {
                    NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
                }
            }
        }
    }
    return self;
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    self.locationCompled(newLocation);
    [_cllocationManager stopUpdatingLocation];
}


-(void)updateCurrentLocation:(GKFetchLocationCompledBlock)compled
{
    self.locationCompled = [compled copy];
     [_cllocationManager startUpdatingLocation];
}

@end
